/*
 * @Author: libing 9852442+liu-sheng-8667@user.noreply.gitee.com
 * @Date: 2024-05-23 20:46:26
 * @LastEditors: xuezhuangzhuang xzz6996@qq.com
 * @LastEditTime: 2025-04-13 14:17:40
 * @FilePath: \crm\config\request.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { getToken } from "@/config/storage";
import global from "@/config/global";
const DURATION = 2000;


const goLogin = () => {
  uni.clearStorageSync()
  uni.reLaunch()
  uni.navigateTo({
   url: "/pages/login/index"
  })
};

/**
 * 统一请求的地方
 * @param {*} path 后端路径
 * @param {*} method 请求方式
 * @param {*} params 参数
 * @param {*} header 扩充请求头
 * @param {*} needSucMsg 接口成功之后是否需要弹出成功信息
 * @param {*} needDeepData 是否返回res.data.data, 否则返回res.data
 * @returns promise
 */

export function service({
  path = "",
  method = "POST",
  params = {},
  header = {},
  needSucMsg = false,
  needDeepData = true,
  timeout = 10000,
}) {
  let promise = new Promise((resolve, reject) => {
    uni.request({
      url: global.baseUrl + path,
      data: {
        ...params,
      },
      dataType: "json",
      header: {
        "Tenant-Id": 1,
        // request拦截器
        Authorization:'Bearer ' + getToken(), // 让每个请求携带自定义token 请根据实际情况自行修改
        // "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8", //自定义请求头信息
        // Authorization: "Basic Y3VzdG9tOmN1c3RvbQ==",
        //  "Bearer " + getToken(),
        ...header,
      },
      timeout,
      method: method,
      success(res) { 
        const { msg, code, access_token } = res.data; 
        if([424, 401].includes(res.statusCode)) {
          uni.showToast({
            icon: "none",
            title: msg || "失败",
            duration: DURATION,
          });
          goLogin()
          return
        }
        if (global.SUCCESS_CODE.includes(code) || access_token) {
          if (needSucMsg) {
            uni.showToast({
              icon: "none",
              title: msg,
            });
          }
          // 成功
          resolve(needDeepData ? res.data.data : res.data);
        } else {
          uni.showToast({
            icon: "none",
            title: msg || "失败",
            duration: DURATION,
          });
          reject(res.data); 
        }
      },
      fail(res) {
        const msg = res.data?.message || res.errMsg || "失败";
        uni.showToast({
          icon: "none",
          title: msg,
          duration: DURATION,
        });
        reject(res);
        console.error("错误结果：", res);
      },
    });
  });
  return promise;
}
